package org.example.rabbitmq.exchangeTopic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class Consumer {

    private static Runnable runnable = () -> {
        // 1: 创建连接工厂，设置连接属性
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        Connection connection = null;
        Channel channel = null;
        try {
            // 2: 创建连接，获取通道（消费者一般不增加自动关闭）
            connection = connectionFactory.newConnection("消费者");
            channel = connection.createChannel();
            // 获取队列的名称
            final String queueName = Thread.currentThread().getName();

            // 6： 定义接受消息的回调
            channel.basicConsume(queueName, true,
                    (consumerTag, delivery) -> System.out.println(queueName + "：收到消息是：" + new String(delivery.getBody(), "UTF-8")),
                    consumerTag -> {
                    });
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送消息出现异常...");
        } finally {
            // 此处应该是需要关闭通道的，不过为了测试咱们不关闭了
        }
    };

    public static void main(String[] args) {
        // 启动三个线程去执行
        new Thread(runnable, "topic-queue1").start();
        new Thread(runnable, "topic-queue2").start();
        new Thread(runnable, "topic-queue3").start();
    }
}
